
module aoesky {
	/**
	 * @class aoesky.SkeletonSprite
	 * @classdesc
     * Bitmap 类表示用于spine骨骼动画的显示对象。
	 * @extends egret.DisplayObject
	 */
    export class SkeletonSprite extends egret.DisplayObject {

        

        public constructor() {
            super();
        }
        private _texture:egret.Texture;
        //这个是同步的方法，但是需要提前加载好资源
        public initWithTexture(atlasText:string,jsonText:string,_texture:egret.Texture):void{
            
            var atlas:any = new spine.Atlas(atlasText,{
                load : function(page,var2,atlas){
                    var texture:egret.Texture = _texture;

                    page.rendererObject = texture;
                    page.width = texture.textureWidth;
                    page.height = texture.textureHeight;
                    atlas.updateUVs(page);
                },
                unload :function(var1){

                }
            });
            //
            this.createSkeleton(atlas,jsonText);

        }
        //此方法会根据atlasText的信息去异步加载图片，加载完成之后会发送事件
        public initAsny(atlasText:string,jsonText:string,preFix:string):void{
            var count = 0;
            var atlas2:any = new spine.Atlas(atlasText,{
                load : function(page,var2,atlas){
                    count ++;
                    RES.getResByUrl(preFix+var2,function(texture){
                        count--;
                        page.rendererObject = texture;
                        page.width = texture.textureWidth;
                        page.height = texture.textureHeight;
                        atlas.updateUVs(page);
                        if(count == 0){
                            this.createSkeleton(atlas2,jsonText);
                        }
                    },this,RES.ResourceItem.TYPE_IMAGE)

                },
                unload :function(var1){
                    console.log("unload");
                }
            });

               
        }
        private skeleton:any;
        private checkError():any{
            if(this.skeleton == null){
                egret.Logger.fatal("骨骼对象还没有创建");
                return true;
            }
            return false;            
        }
        
        private state:any;
        private stateData:any;
        private lastTime:number;
        private createSkeleton(atlas:any,jsonText:any):void{
            var spineJson:string =  jsonText;
            var json:any = new spine.SkeletonJson(new spine.AtlasAttachmentLoader(atlas));
            var skeletonData:any = json.readSkeletonData(JSON.parse(spineJson));
            spine.Bone.yDown = true;

            this.skeleton = new spine.Skeleton(skeletonData);
            this.skeleton.x = 0;
            this.skeleton.y = 0;
            this.skeleton.updateWorldTransform();

            this.stateData = new spine.AnimationStateData(skeletonData); 
            this.state = new spine.AnimationState(this.stateData);

            
            this.lastTime = egret.getTimer();
                
            this.addEventListener(egret.Event.ENTER_FRAME,this.UpdateHandler,this);
            //发送事件 todo
        }
        public setMixByName(str1:string,str2:string,delay:number):void{
            if (this.checkError()) return;
            this.stateData.setMixByName(str1, str2, delay);
        }
        public setAnimationByName(delay:number,animationName:string,repeat:any):void{
            if (this.checkError()) return;
            this.state.setAnimationByName(delay, animationName, repeat);
        }
        private timeScale = 1;
        public setTimeScale(scale:number):void{
            this.timeScale = scale;
        }
        public UpdateHandler(event:egret.Event):void{
            var nowTime:number = egret.getTimer();
            var delta:number = nowTime - this.lastTime;
            this.state.update(delta/1000*this.timeScale);
            this.state.apply(this.skeleton);
            this.skeleton.updateWorldTransform();
            this.lastTime = nowTime;
        }
        /**
        public get x():number {
            return this._x;
        }

        public set x(value:number) {
            this._setX(value);
        }

        public get y():number {
            return this._x;
        }

        public set y(value:number) {
            this._setX(value);
        }
        */

        public _render(renderContext:egret.RendererContext):void {
           var skeleton = this.skeleton;
            if(skeleton){
                //render the spine
                
                var drawOrder = skeleton.drawOrder;
                var _worldTransform = new egret.Matrix();
                for (var i = 0, n = drawOrder.length; i < n; i++) {
                    var slot:any = drawOrder[i];
                    var attachment:any = slot.attachment;
                    if (!(attachment instanceof spine.RegionAttachment)) continue;
                    var vertices = [];
                    attachment.computeVertices(skeleton.x, skeleton.y, slot.bone, vertices);
                    //处理渲染
                    var x = vertices[2];
                    var y = vertices[3];
                    var w = attachment.rendererObject.width;
                    var h = attachment.rendererObject.height;
                    var px = attachment.rendererObject.x;
                    var py = attachment.rendererObject.y;
                    
                    var scaleX = attachment.scaleX;
                    var scaleY = attachment.scaleY;
                    //var angle = -(slot.bone.worldRotation + attachment.rotation) * Math.PI/180;
                    var angle = -(slot.bone.worldRotation + attachment.rotation);
                    
                    if(skeleton.flipX) {
                        
                        scaleX *= -1;
                        angle *= -1;
                    }

                    if(skeleton.flipY) {
                        
                        scaleY *= -1;
                        angle *= -1;
                    }

                    _worldTransform.identityMatrix(this._worldTransform);
                    _worldTransform.appendTransform(x, y, scaleX, scaleY, angle,0, 0, 0, 0);
                    renderContext.setTransform(_worldTransform);
                    //renderContext.canvasContext.
                   // renderContext.canvasContext.translate(x, y);
        //renderContext.canvasContext.rotate(angle);
        //renderContext.canvasContext.scale(scaleX, scaleY);
                    var locTexture =   attachment.rendererObject.page.rendererObject
                    renderContext.drawImage(locTexture, px, py, w, h, 0, 0, w, h);
                }

            }
        }

        /**
         * @see egret.DisplayObject.measureBounds
         * @returns {egret.Rectangle}
         * @private
         */
        public _measureBounds():egret.Rectangle {
            var texture:egret.Texture = this._texture;
            if(!texture){
                return super._measureBounds();
            }
            var x:number = texture._offsetX;
            var y:number = texture._offsetY;
            var w:number = texture._textureWidth;
            var h:number = texture._textureHeight;
            return egret.Rectangle.identity.initialize(x,y, w, h);
        }
    }
}